import Vue from 'vue'
import Vuex from 'vuex'
import $http from '../common/http.js'
import createPersistedState from "vuex-persistedstate"

Vue.use(Vuex)

const store = new Vuex.Store({
	state: {
		token: '',
		user: {},
		login: false
	},
	getters: {
		token: state => {
			return uni.getStorageSync('token') || '';
		},
		login: state => {
			return state.login || !! state.token
		},
		user: state => {
			console.log(state);
			return state.user || {}
		}
	},
	mutations: { // 同步（commit）
		login(state, data) { // 异步同步登录
			state.token = data.token;
			state.login = !!data.token;
			uni.setStorageSync('token', data.token);
		},
		profile(state, data) { // 用户信息
			state.user = data.user;
			state.login = !!data.user;
			state.token = uni.getStorageSync('token');
			console.log('commit', 'user');
			console.log(state);
		},
		logout(state) { // 同步退出
			uni.removeStorageSync('token');
			state.token = !!0;
			state.login = !!0;
			state.user = {};
		}
	},
	actions: { // 异步（dispatch）传递 > mutations > state
		// login({commit,state},params){ // 异步登录
		// 	// console.log('store参数：',params,$http);
		// 	$http.httpReq({url:'api/member/index',token:''})
		// 	.then(res=>{
		// 		console.log(res);
		// 		commit('login',{token:res.data.data.token});
		// 	})
		// 	.catch(err=>{
		// 		console.log(err);
		// 	})
		// },
		profile({
			commit,
			state
		}, params) {
			$http.httpReq({
					url: 'api/member/index',
					token: ''
				})
				.then(res => {
					console.log('dipatch', 'commit','profile');
					commit('profile', {
						user: res.data.data.member
					});
				})
				.catch(err => {
					console.log(err);
				})
		}
	},
	// 默认是localStorage
	plugins: [createPersistedState({
		storage: window.sessionStorage
	})]
})

export default store
